import { useRoutes, useNavigate, useLocation, Outlet } from "react-router-dom";
import { Suspense, lazy, useEffect, useState } from 'react'
import { Loading } from '../component'

// 页面组件
const Login        = lazy(() => import(/* webpackChunkName: 'login' */        '../page/Login'))

const Home         = lazy(() => import(/* webpackChunkName: 'home' */         '../page/Home'))
const Project      = lazy(() => import(/* webpackChunkName: 'project' */      '../page/Project'))
const AddProject   = lazy(() => import(/* webpackChunkName: 'addproject' */   '../page/Project/Add'))
const EditProject  = lazy(() => import(/* webpackChunkName: 'editproject' */  '../page/Project/Edit'))

const User         = lazy(() => import(/* webpackChunkName: 'user' */         '../page/User'))

const Role         = lazy(() => import(/* webpackChunkName: 'role' */         '../page/Role'))

const Settings     = lazy(() => import(/* webpackChunkName: 'settings' */     '../page/Settings'))
const Notification  = lazy(() => import(/* webpackChunkName: 'notification' */  '../page/Notification'))
const Profile       = lazy(() => import(/* webpackChunkName: 'profile' */       '../page/Profile'))
const NoAuth       = lazy(() => import(/* webpackChunkName: 'noauth' */       '../page/NoAuth'))
const NotFound     = lazy(() => import(/* webpackChunkName: 'notfound' */     '../page/NotFound'))


// 路由的数据结构
interface IRouter {
  path: string,
  component: any,
  title?: string,
  icon?: any,
  auth?: boolean,
  exact?: boolean,
  isNav?: boolean,
  children?: Array<IRouter>,
}

// 未登录页面路由
const mainRoutes: Array<IRouter> = [{
  path: '/',
  component: Login,
  title: '登录',
  auth: false
}, {
  path: '*',
  component: NotFound,
  title: '404',
  auth: false
}]

// 管理页面路由（已登录）
const adminRoutes: Array<IRouter> = [{
  path: 'admin',
  component: Home,
  title: '首页',
  icon: 'dashboard',
  isNav: true,
  auth: false
},
{
  path: 'admin/project',
  component: Project,
  title: '项目',
  icon: 'unordered-list',
  isNav: true,
  exact: true,
  auth: false,
},
{
  path: 'admin/project/add',
  component: AddProject,
  title: '新建项目',
  icon: 'unordered-list',
  isNav: false,
  exact: true,
  auth: false
},
{
  path: 'admin/project/edit/:id',
  component: EditProject,
  title: '项目',
  icon: 'unordered-list',
  isNav: false,
  exact: true,
  auth: false,
},
{
  path: 'admin/user',
  component: User,
  title: '用户',
  icon: 'unordered-list',
  isNav: true,
  exact: true,
  auth: false,
},
{
  path: 'admin/role',
  component: Role,
  title: '角色',
  icon: 'unordered-list',
  isNav: true,
  exact: true,
  auth: false,
},
{
  path: 'admin/settings',
  component: Settings,
  title: '设置',
  icon: 'unordered-list',
  isNav: true,
  exact: true,
  auth: false
},
{
  path: 'admin/notification',
  component: Notification,
  title: '无权查看',
  auth: false
},
{
  path: 'admin/noauth',
  component: NoAuth,
  title: '无权查看',
  auth: false
},
{
  path: 'admin/profile',
  component: Profile,
  title: '个人资料',
  auth: true
}
]

// 根据路径获取路由
const checkAuth = (routers: any, path: string) => {
  for (const data of routers) {
    if (data.path === path) return data
    if (data.children) {
      const res: any = checkAuth(data.children, path)
      if (res) return res
    }
  }

  return null
}

// 路由处理方式
const generateRouter = (routes: Array<IRouter>) => {
  return routes.map((item: any, index: number) => {
    if (item.children) {
      item.children = generateRouter(item.children)
    }
    // 路由懒加载
    item.element = <Suspense fallback={<Loading />}><item.component /></Suspense>

    return item
  })
}

const checkRouterAuth = (path: string)=>{
  let auth = null
  auth = checkAuth(adminRoutes, path)
  return auth
}

const RouterBeforeEach = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const [auth, setAuth] = useState(false)

  useEffect(() => {
    let obj = checkRouterAuth(location.pathname)
    let blLogin = sessionStorage.getItem('login')
    if (obj && obj.auth && blLogin === 'false') {
      setAuth(false)
      navigate('/', { replace: true })
    } else {
      setAuth(true)
    }
  }, [])

  return auth ? <Outlet /> : <NoAuth />
}
 

const MainRouter = generateRouter(mainRoutes)
const AdminRouter = () => useRoutes(generateRouter(adminRoutes))

export { 
  adminRoutes,
  MainRouter,
  AdminRouter
}